﻿using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using DataAccess.DB;
using DuocThaiBinh.Filters;
using DuocThaiBinh.Models;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;

namespace DuocThaiBinh.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();
        
        //
        // GET: /Account/
        [Authorize(Roles = "Administrator")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Administrator")]
        public JsonResult IndexGet()
        {
            var accs = db.UserProfiles.OrderBy(p => p.UserName).Where(p => p.Status).ToList();

            return Json(new
            {
                data = accs.Select(x => new { UserName = x.UserName, Code = x.Code, DisplayName = x.DisplayName, CuaHangs = x.UserInCuaHangs.ToList().Select(y => y.CuaHang.TenCuaHang), ID = x.UserId })
            }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Account/
        [Authorize(Roles = "Administrator")]
        public ActionResult Lock(int id)
        {
            UserProfile user = db.UserProfiles.Find(id);
            if (user != null)
            {
                user.Status = false;
                db.Entry(user).State = EntityState.Modified;
            }

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                UserProfile user = db.UserProfiles.Find(WebSecurity.GetUserId(model.UserName));
                if (user.Status)
                {
                    UserInCuaHangController userInKhoController = new UserInCuaHangController();
                    if (user.UserInCuaHangs.Count == 0)
                    {
                        WebSecurity.Logout();
                        ModelState.AddModelError("", "Tài khoản không được truy cập vào cửa hàng nào. Vui lòng liên hệ admin.");
                        return View(model);
                    }
                    else
                    {
                        Session["CuaHangID"] = user.UserInCuaHangs.FirstOrDefault().CuaHangID;
                        return RedirectToLocal(returnUrl);
                    }
                }
                else
                {
                    WebSecurity.Logout();
                    ModelState.AddModelError("", "Tài khoản đang bị khóa. Vui lòng liên hệ admin.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không đúng.");
            }

            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [Authorize(Roles = "Administrator")]
        public ActionResult Create()
        {
            ViewBag.CuaHangs = db.CuaHangs.ToList();
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(UserProfile model, string IsNguoiXuatKho, string IsNguoiNhapKho, int[] khoes)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    if (!WebSecurity.UserExists(model.UserName))
                    {
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Status = true, DisplayName = model.DisplayName, Code = model.Code}, false);
                        if (Convert.ToBoolean(IsNguoiXuatKho))
                        {
                            if (!Roles.IsUserInRole(model.UserName, "StaffXuatKho"))
                            {
                                Roles.AddUserToRole(model.UserName, "StaffXuatKho");
                            }
                        }
                        if (Convert.ToBoolean(IsNguoiNhapKho))
                        {
                            if (!Roles.IsUserInRole(model.UserName, "Staff"))
                            {
                                Roles.AddUserToRole(model.UserName, "Staff");
                            }
                        }
                    }

                    UserInCuaHangController userInCuaHangController = new UserInCuaHangController();
                    userInCuaHangController.UpdateByUser(WebSecurity.GetUserId(model.UserName), khoes);
                    
                    return RedirectToAction("Index", "Account");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            ViewBag.CuaHangs = db.CuaHangs.ToList();

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/Edit
        public ActionResult Edit(int id = 0)
        {
            if (id == 0)
            {
                id = WebSecurity.GetUserId(User.Identity.Name);
            }
            else if (WebSecurity.GetUserId(User.Identity.Name) != id && !Roles.GetRolesForUser(User.Identity.Name).Contains("Administrator"))
            {
                return RedirectToAction("Index", "Home");
            }
            UserProfile user = db.UserProfiles.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }

            user.Password = "sssssss"; ////set any text to pass required validation, this value will not be saved to database
            user.ConfirmPassword = "sssssss";

            ViewBag.CuaHangs = db.CuaHangs.ToList();
            return View(user);
        }
        
        //
        // POST: /Account/Edit

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(UserProfile model, string IsNguoiXuatKho, string IsNguoiNhapKho, int[] khoes)
        {
            if (WebSecurity.GetUserId(User.Identity.Name) != model.UserId && !Roles.GetRolesForUser(User.Identity.Name).Contains("Administrator"))
            {
                return RedirectToAction("Index", "Home");
            }

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    db.Entry(model).State = EntityState.Modified;
                    db.SaveChanges();
                    if (Roles.GetRolesForUser(User.Identity.Name).Contains("Administrator"))
                    {
                        if (Convert.ToBoolean(IsNguoiXuatKho))
                        {
                            if (!Roles.IsUserInRole(model.UserName, "StaffXuatKho"))
                            {
                                Roles.AddUserToRole(model.UserName, "StaffXuatKho");
                            }
                        }
                        else
                        {
                            if (Roles.IsUserInRole(model.UserName, "StaffXuatKho"))
                            {
                                Roles.RemoveUserFromRole(model.UserName, "StaffXuatKho");
                            }
                        }

                        if (Convert.ToBoolean(IsNguoiNhapKho))
                        {
                            if (!Roles.IsUserInRole(model.UserName, "Staff"))
                            {
                                Roles.AddUserToRole(model.UserName, "Staff");
                            }
                        }
                        else
                        {
                            if (Roles.IsUserInRole(model.UserName, "Staff"))
                            {
                                Roles.RemoveUserFromRole(model.UserName, "Staff");
                            }
                        }

                        UserInCuaHangController userInKhoController = new UserInCuaHangController();
                        userInKhoController.UpdateByUser(model.UserId, khoes);

                        return RedirectToAction("Index", "Account");
                    }

                    return RedirectToAction("Edit", "Account");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult ResetPassword(ManageMessageId? message)
        {
            return View();
        }

        [Authorize(Roles = "Administrator")]
        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(model.UserName));
            if (hasLocalAccount)
            {
                var token = WebSecurity.GeneratePasswordResetToken(model.UserName);
                var confirmationToken = WebSecurity.ResetPassword(token, "abcde12345-");
                if (confirmationToken)
                {
                    ViewBag.StatusMessage = "bạn đã reset password thành công";
                }
                else {
                    ViewBag.StatusMessage = "bạn đã reset password thất bại, hãy làm lại";
                }
            }

            return View();           
        }

        //
        // GET: /Account/ChangePassword

        public ActionResult ChangePassword(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Bạn đã thay đổi mật khẩu thành công."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("ChangePassword");
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("ChangePassword");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("ChangePassword", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("ChangePassword", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
